import datetime
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from orders.models import OrderInfo,OrderGoods
from tools.response_code import RETCODE
from tools.utils import get_category,get_breadcrumb
from tools import constants
from goods.models import GoodsCategory, SKU, GoodsVisitCount
import logging
logger = logging.getLogger('django')
class ListView(View):
    '''商品的列表页'''
    def get(self,request,category_id,page_num):
        # 分类导航菜单
        categories = get_category()
        try:
            category = GoodsCategory.objects.get(id = category_id)
        except GoodsCategory.DoesNotExist as e:
            logger.error(e)
            return render(request,'404.html')
        # 获取面包屑导航
        breadcrumb = get_breadcrumb(category)
        # 接收一下查询字符串，判断根据什么排序输出商品
        sort = request.GET.get('sort')
        print('jiesh')
        if sort == 'price':
            sort_field = 'price' # 价格按照升序排列
        elif sort == 'hot':
            sort_field = '-sales' # 销量就按照降序排列
        else:
            sort_field = '-create_time' # 默认就是按照商品创建时间降序排列

        # 根据category——id 去筛选出所有该分类下的上架的商品，并按照sort要求排序
        skus = SKU.objects.filter(category_id=category_id,is_launched=True).order_by(sort_field)
        # 分页功能
        paginator = Paginator(skus,constants.GOODS_LIST_LIMIT)
        try:
            page_skus = paginator.page(page_num) # 每一页的内容，page——num 是第几页
        except Exception as e:
            logger.error(e)
            return render(request,'404.html')
        # 一共有多少页
        total_page = paginator.num_pages
        return render(request,'list.html',locals())


class HotView(View):
    '''热销排行'''
    def get(self,request,category_id):
        # 通过前端传递的 category_id 查询到该分类下所有的sku ，并且按照销量排序，取前两名
        skus = SKU.objects.filter(category_id = category_id,is_launched=True).order_by('-sales')[:2]
        # 前端通过ajax发送的请求，响应也是ajax来接收，数据
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image':sku.default_image.url,
                'price':sku.price
            })
        # 响应数据
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok','hot_skus':hot_skus})


class DetailView(View):
    '''商品详情页'''
    def get(self,request,sku_id):
        # 商品分类导航
        categories = get_category()
        # 面包屑导航
        # 先通过sku——id 找到具体的商品，然后再找到他的三级分类
        try:
            sku = SKU.objects.get(id= sku_id)
        except SKU.DoesNotExist as e:
            logger.error(e)
            return render(request,'404.html')
        category = sku.category
        spu = sku.spu
        # 主备当前商品的规格数据id列表
        current_sku_spec_qs = sku.specs.all()
        current_sku_option_ids =[]  # [1, 4, 7] 当前的sku这款商品的规格值id列表
        for current_sku_spec in current_sku_spec_qs:
            current_sku_option_ids.append(current_sku_spec.option_id)

        # 构造一个规格选择的一个仓库或者叫图集
        # 获取当前spu下的所有sku
        temp_sku_qs = spu.sku_set.all()
        #预先定义一个存放图集的字典
        spec_sku_map = {}
        for temp_sku in temp_sku_qs:
            # temp_spec_qs 是 当前temp_sku sku的对象的所有规格查询集
            temp_spec_qs = temp_sku.specs.all().order_by('spec_id')
            temp_sku_spec_option_ids = []
            for temp_spec in temp_spec_qs:
                temp_sku_spec_option_ids.append(temp_spec.option_id)

            spec_sku_map[tuple(temp_sku_spec_option_ids)]= temp_sku.id
        print(spec_sku_map)

        # 查询当前spu的所有规格名称 spu_specs_qs是查询集 <QuerySet [<SPUSpecification: Apple iPhone 8 Plus: 颜色>, <SPUSpecification: Apple iPhone 8 Plus: 内存>]>
        spu_specs_qs = spu.specs.all().order_by('id')
        for index,spu_spec in enumerate(spu_specs_qs):
            # spu_options_qs 是每一个spu的规格标签对应的具体规格 <QuerySet [<SpecificationOption: Apple iPhone 8 Plus: 颜色 - 金色>, <SpecificationOption: Apple iPhone 8 Plus: 颜色 - 深空灰>, <SpecificationOption: Apple iPhone 8 Plus: 颜色 - 银色>]>
            spu_options_qs = spu_spec.options.all()
            # 给每一个规格标签 添加一个选项的属性,属性名字叫sepc_option ，存放的是当前的规格名称下的所有的选项的查询集
            spu_spec.sepc_option = spu_options_qs
            # 复制一个当前sku的选项列表 需要一个浅拷贝的
            temp_option_ids = current_sku_option_ids[:] #
            for spu_option in spu_options_qs:
                # 遍历当前规格选项
                temp_option_ids[index]=spu_option.id
                # 再给每一个spu的选项绑定一个sku_id 属性
                spu_option.sku_id = spec_sku_map.get(tuple(temp_option_ids))

        breadcrumb = get_breadcrumb(category)
        return render(request,'detail.html',locals())


def VisitlView(request,category_id):
    if request.method == 'POST':
        # 通过category_id 去数据库中查询一下，有没有符合条件的记录 ，
        # 如果有在原来的记录中加一，如果没有就创建一条记录
        visit_obj,created = GoodsVisitCount.objects.get_or_create(category_id = category_id,date = datetime.datetime.today())
        if created:
            # 说明表中原来没有满足条件的记录，刚刚创建了一条，但是没有count
            visit_obj.count = 1
            visit_obj.save()
        else:
            visit_obj.count += 1
            visit_obj.save()
        return JsonResponse({'code':RETCODE.OK,'errmsg':'添加访问量成功'})


class GoodsCommentsView(View):
    '''商品评价信息'''
    def get(self,request,sku_id):
        # 应该去order_goods 表中查，所有评价过的记录
        order_goods_list = OrderGoods.objects.filter(sku_id=sku_id,is_commented=True).order_by('-create_time')[:20]
        comment_list = []
        for order_goods in order_goods_list:
            # order_goods表中没有用户名，去order_info表中去查---user表中
            username = order_goods.order.user.username
            comment_list.append({
                # 用三元运算符 来设置用户名，如果是匿名用户，则显示* 的用户名，否则 显示 全名
                'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username,
                'comment':order_goods.comment,
                'score':order_goods.score
            })
        return JsonResponse({'code':RETCODE.OK,'errmsg':'获取评价信息成功','comment_list':comment_list})
